package com.xhwl.logistics.service.impl.http;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.common.exception.ApplicationException;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.utils.StringUtils;
import com.xhwl.logistics.bo.cent.VehicleIntegratedConfigBO;
import com.xhwl.logistics.constant.LiFangConstant;
import com.xhwl.logistics.dto.http.CarSpotStatDaHuaDTO;
import com.xhwl.logistics.dto.http.ParkingLotAreaInfoDaHuaDTO;
import com.xhwl.logistics.dto.http.PassageAndDeviceDaHuaDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Description: 车行对接立方接口
 * @Author: wangyiling
 * @Date: 2023/04/13
 */
@Slf4j
//@Service
public class LiFangHttpServiceImpl {

    /**
     * 获取车场统计基本数据
     * @param vehicleIntegratedConfigBO
     * @return
     */
    public CarSpotStatDaHuaDTO getCarSpotStat(VehicleIntegratedConfigBO vehicleIntegratedConfigBO){
        HashMap<String, Object> params = new HashMap<>();
        params.put("stationNo",LiFangConstant.VEHICLE_STATION_NO);

        JSONObject resultObject = post(LiFangConstant.VEHICLE_PARKING_LOT_URL, params, vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProductId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getUser(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getPassword());
        if (resultObject == null) {
            return null;
        }
        if (!"0".equals(resultObject.getString("resCode"))) {
            log.error("post path:{};params:{};errMsg:{}", LiFangConstant.VEHICLE_PARKING_LOT_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return null;
        }
        CarSpotStatDaHuaDTO carSpotStatDaHuaDTO = new CarSpotStatDaHuaDTO();
        carSpotStatDaHuaDTO.setTotalLot(resultObject.getInteger("totalNum"));
        carSpotStatDaHuaDTO.setIdleLot(resultObject.getInteger("totalRemainNum"));
        return carSpotStatDaHuaDTO;
    }

    /**
     * 调用立方接口，获取停车场（区域）基本信息列表
     * @param vehicleIntegratedConfigBO
     * @return
     */
    public List<ParkingLotAreaInfoDaHuaDTO> getParkingLotAreaInfo(VehicleIntegratedConfigBO vehicleIntegratedConfigBO){
        HashMap<String, Object> params = new HashMap<>();
        params.put("stationNo",LiFangConstant.VEHICLE_STATION_NO);
        JSONObject resultObject = post(LiFangConstant.VEHICLE_PARKING_LOT_URL, params, vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProductId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getUser(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getPassword());
        if (resultObject == null) {
            return null;
        }
        if (!"0".equals(resultObject.getString("resCode"))) {
            log.error("post path:{};params:{};errMsg:{}", LiFangConstant.VEHICLE_PARKING_LOT_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return null;
        }
        List<ParkingLotAreaInfoDaHuaDTO> parkingLotAreaInfoDaHuaDTOS = new ArrayList<>();
        JSONArray parkArray = resultObject.getJSONArray("parkingLotInfo");
        parkArray.forEach(park->{
            ParkingLotAreaInfoDaHuaDTO parkingLotAreaInfoDaHuaDTO = new ParkingLotAreaInfoDaHuaDTO();
            JSONObject parkData = JSONObject.parseObject(park.toString());
            parkingLotAreaInfoDaHuaDTO.setId(parkData.getString("parkingLotId"));
            parkingLotAreaInfoDaHuaDTO.setParkingLot(parkData.getString("parkingLotName"));
            parkingLotAreaInfoDaHuaDTO.setTotalLot(parkData.getInteger("totalNum"));
            parkingLotAreaInfoDaHuaDTO.setIdleLot(parkData.getInteger("totalRemainNum"));
            parkingLotAreaInfoDaHuaDTO.setUsedLot(parkData.getInteger("totalStopNum"));
            parkingLotAreaInfoDaHuaDTOS.add(parkingLotAreaInfoDaHuaDTO);
        });
        if (CollectionUtils.isEmpty(parkingLotAreaInfoDaHuaDTOS)) {
            return null;
        }
        return parkingLotAreaInfoDaHuaDTOS;
    }
    /**
     * 获取通道信息
     * @param vehicleIntegratedConfigBO
     * @return
     */
    public List<PassageAndDeviceDaHuaDTO> getPassageList(VehicleIntegratedConfigBO vehicleIntegratedConfigBO){
        HashMap<String, Object> params = new HashMap<>();
        params.put("stationNo",LiFangConstant.VEHICLE_STATION_NO);
        JSONObject resultObject = post(LiFangConstant.VEHICLE_PARKING_CHANNEL_URL , params, vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProductId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getUser(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getPassword());
        if (resultObject == null) {
            return null;
        }
        if (!"0".equals(resultObject.getString("resCode"))) {
            log.error("post path:{};params:{};errMsg:{}", LiFangConstant.VEHICLE_PARKING_CHANNEL_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return null;
        }
        List<PassageAndDeviceDaHuaDTO> passageAndDeviceDaHuaDTOS = new ArrayList<>();
        JSONArray parkArray = resultObject.getJSONArray("channelList");
        parkArray.forEach(channel->{
            PassageAndDeviceDaHuaDTO passageAndDeviceDaHuaDTO = new PassageAndDeviceDaHuaDTO();
            JSONObject channelData = JSONObject.parseObject(channel.toString());
            passageAndDeviceDaHuaDTO.setChannelId(channelData.getString("channelID"));
            passageAndDeviceDaHuaDTO.setTideName(channelData.getString("channelName"));
            passageAndDeviceDaHuaDTO.setCarDirect(channelData.getString("inOrOut"));
            passageAndDeviceDaHuaDTO.setCarDirectStr(channelData.getInteger("inOrOut")==0?"in":"out");
            passageAndDeviceDaHuaDTOS.add(passageAndDeviceDaHuaDTO);
        });
        if (CollectionUtils.isEmpty(passageAndDeviceDaHuaDTOS)) {
            return null;
        }
        return passageAndDeviceDaHuaDTOS;
    }
    public JSONObject post(String url, HashMap<String, Object> params, Integer projectId, Integer productId, String ipAndPort, String admin, String password){
        String path = new StringBuffer(ipAndPort).append(url).toString();
        String result = null;

        log.info("请求立方参数信息:{}", params);
        try {
            result = HttpRequest
                    .post(path)
                    .body(JSON.toJSONString(params))
                    .setConnectionTimeout(3000)
                    .setReadTimeout(5000)
                    .execute()
                    .body();
        } catch (HttpException e) {
            log.error("【LiFang post exception】path:{};params:{}", path, params);
            e.printStackTrace();
            throw new ApplicationException();
        }
        if (StringUtils.isEmpty(result)) {
            log.error("【LiFang post】path:{};params:{};result is null!", path, JSON.toJSONString(params));
            throw new BusinessException();
        }
        JSONObject jsonObject = JSON.parseObject(result);
        log.info("【LiFang post】path:{};params:{};result:{}", path, JSON.toJSONString(params), jsonObject);
        return jsonObject;

    }
}
